/* eslint-disable react-refresh/only-export-components */
import type {FC} from "react";
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button,  Form, Input,message } from 'antd';
import { Link ,useSearchParams,useFetcher} from "react-router-dom";
import type { ActionFunctionArgs } from "react-router-dom";
import {loginApi} from '@/api/auth-api'
import to from "await-to-js";
import { setToken } from "@/store/app-store";


const Login:FC = () =>{

    const [searchParams] = useSearchParams()
    const loginFetcher = useFetcher()
    
    
    const onFinish = (values: LoginForm) => {
        // console.log('Received values of form: ', values);
        loginFetcher.submit(values,{method:'POST'})
      };
    return (
        <>
        <Form size="large"
        initialValues={{username:searchParams.get('uname')}}
      onFinish={onFinish}
    >
      <Form.Item
        name="username"
        rules={[{ required: true, message: '请输入用户名' },
            {pattern:/^[a-zA-Z0-9]{1,10}$/,message:'用户名必须是1-10位的非空字母数字'}
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[{ required: true, message: '请输入密码' },
            {pattern:/^\S{6,15}$/,message:'密码必须是长度6-15的非空字符'}
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="Password"
        />
      </Form.Item>
      
      <Form.Item>
        <Button type="primary" htmlType="submit" loading={loginFetcher.state !=='idle'&&{delay:200}}>
          登录
        </Button>
        Or <Link to="/reg">注册</Link>
      </Form.Item>
    </Form>
        </>
    )
}

export const action =async({ request }:ActionFunctionArgs) =>{
    
    const fd = await request.formData()
    const [err,res] = await to(loginApi(fd))
    
    if(err) return null
    //登录成功跳转后台
    //TODO:全局存储登录成功后拿到的token
    console.log(res);
    setToken(res.token)
    message.success(res.message)
    // return redirect('/')
    return null
}

export default Login